package com.tkjt.pms.impt.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tkjt.pms.common.entity.*;
import com.tkjt.pms.common.utils.EsBeanUtils;
import com.tkjt.pms.common.utils.EsJsonUtils;
import com.tkjt.pms.impt.IKpiMirrorUpdaterService;
import com.tkjt.pms.impt.common.KpiImportRepositories;
import com.tkjt.pms.impt.common.KpiImportUtils;
import com.tkjt.pms.impt.vos.KpiIndexDataVo;
import com.tkjt.pms.impt.vos.KpiIndexValueVo;
import com.tkjt.pms.modules.common.mapper.*;
import com.tkjt.pms.modules.common.service.TkIndexValueMirrorServiceI;
import com.tkjt.pms.modules.common.service.TkIndexWeightMirrorService;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.entity.SysUserDepart;
import org.jeecg.modules.system.service.ISysDepartService;
import org.jeecg.modules.system.service.ISysUserDepartService;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.Map.Entry;

@Slf4j
@Service
public class KpiMirrorUpdater extends ServiceImpl<TkIndexValueMapper, TkIndexValue> implements IKpiMirrorUpdaterService {

	@Autowired
	PMSCommonMapper commonMapper;
    @Autowired
	TkIndexValueMirrorServiceI tkIndexValueMirrorServiceI;
    @Autowired
    TkIndexWeightMirrorService tkIndexWeightMirrorService;
	@Autowired
	SysUserDepartMirrorMapper sysUserDepartMirrorMapper;
	@Autowired
	SysUserMirrorMapper sysUserMirrorMapper;
	@Autowired
	SysDepartMirrorMapper sysDepartMirrorMapper;
	@Autowired
	TkDepartGroupMirrorMapper tkDepartGroupMirrorMapper;

    @Override
	public void updateIndexWeightMirror(String mirrorCode, String indexGroup, String indexCode, String orgName, String valueStr) {

		valueStr = KpiImportUtils.formatValueStr(valueStr);

		String orgCode = KpiImportRepositories.org2Codes.get(orgName);
		if(StringUtils.isEmpty(orgCode)) {
			log.error("orgCode==null, indexCode=" + indexCode);
			System.exit(0);
		}
		String indexType = KpiImportRepositories.indexTypes.get(indexCode);
		if(StringUtils.isEmpty(indexType)) {
			log.error("indexType==null, indexCode=" + indexCode + ",orgCode="+orgCode);
			System.exit(0);
		}
		log.info("indexCode="+indexCode+",orgName="+orgName);
		// 权重表
		TkIndexWeightMirror entity = new TkIndexWeightMirror();
		entity.setMirrorCode(mirrorCode);
		entity.setWeightY("2019");
		entity.setIndexGroup(indexGroup);
		entity.setIndexType(indexType);
		entity.setIndexCode(indexCode);
		entity.setOrgCode(orgCode);
		
		if (valueStr.indexOf('[') >= 0 && valueStr.indexOf(']') > 0) {
			entity.setWeightFormat(2);
		} else {
			entity.setWeightFormat(1);
			valueStr = KpiImportUtils.formatWeightStr("1", valueStr);
		}
		
		entity.setWeightM01(valueStr);
		entity.setWeightM02(valueStr);
		entity.setWeightM03(valueStr);
		entity.setWeightM04(valueStr);
		entity.setWeightM05(valueStr);
		entity.setWeightM06(valueStr);
		entity.setWeightM07(valueStr);
		entity.setWeightM08(valueStr);
		entity.setWeightM09(valueStr);
		entity.setWeightM10(valueStr);
		entity.setWeightM11(valueStr);
		entity.setWeightM12(valueStr);

		entity.setCreateBy("admin");
		entity.setCreateDate(new Date());
		entity.setUpdateBy("admin");
		entity.setUpdateDate(new Date());

		updateWeightMirrorEntity(entity);

	}
	@Override
	public void updateIndexValueDataMirror(String mirrorCode, String indexCode, String orgName, List<KpiIndexDataVo> indexData, List<KpiIndexValueVo> indexValues) {
		int ivSize = indexValues.size();
		if (ivSize != indexData.size()) {
			log.error("indexCode=" + indexCode + ", orgName=" + orgName + ", indexValue size:" + ivSize + ", index data size:" + indexData.size());
			System.exit(0);
		}
		String indexOrgCode = KpiImportRepositories.org2Codes.get(orgName);
		log.info("mirrorCode=" + mirrorCode + ",indexCode=" + indexCode + ",orgCode=" + indexOrgCode + ", orgName=" + orgName + ", indexValue size:" + ivSize);
		if(StringUtils.isEmpty(indexOrgCode)) {
			log.error("orgCode==null, indexCode=" + indexCode + ",orgName="+orgName);
			System.exit(0);
		}
		this.updateIndexValueMirrorEntity(mirrorCode, indexCode, indexOrgCode, indexValues, indexData);
	}

	private void updateIndexValueMirrorEntity(String mirrorCode, String indexCode, String indexOrgCode, List<KpiIndexValueVo> indexValues, List<KpiIndexDataVo> indexDatas) {
		SysDepartMirror depart = sysDepartMirrorMapper.selectOne(new QueryWrapper<SysDepartMirror>().lambda().eq(SysDepartMirror::getOrgCode,indexOrgCode).eq(SysDepartMirror::getMirrorCode,mirrorCode.substring(0,6)));
		if(depart != null){
			TkDepartGroupMirror tkDepartGroupMirror = tkDepartGroupMirrorMapper.selectOne(new QueryWrapper<TkDepartGroupMirror>().lambda().eq(TkDepartGroupMirror::getIndexDepart,indexOrgCode).eq(TkDepartGroupMirror::getMirrorCode,mirrorCode.substring(0,6)));
			if("ATRV0000".equals(tkDepartGroupMirror.getDepartAttr())){
				SysUserMirror sysUser = new SysUserMirror();
				sysUser.setUsername("system");
				updateIndexValueMirroEntityCommonWay(mirrorCode,indexCode,indexOrgCode,indexValues,indexDatas,sysUser);
			}else{
				List<SysUserDepartMirror> userDeparts = sysUserDepartMirrorMapper.selectList(new QueryWrapper<SysUserDepartMirror>().lambda().eq(SysUserDepartMirror::getDepId,depart.getId()).eq(SysUserDepartMirror::getMirrorCode,mirrorCode.substring(0,6)));
				for(SysUserDepartMirror userDepart : userDeparts){
					SysUserMirror scorer =sysUserMirrorMapper.selectOne(new QueryWrapper<SysUserMirror>().lambda().eq(SysUserMirror::getId,userDepart.getUserId()).eq(SysUserMirror::getMirrorCode,mirrorCode.substring(0,6)));
					updateIndexValueMirroEntityCommonWay(mirrorCode,indexCode,indexOrgCode,indexValues,indexDatas,scorer);
				}
			}
		}



	}

	private void updateIndexValueMirroEntityCommonWay(String mirrorCode, String indexCode, String indexOrgCode, List<KpiIndexValueVo> indexValues, List<KpiIndexDataVo> indexDatas,SysUserMirror scorer){
		QueryWrapper<TkDepartGroupMirror> groupQueryWrapper = new QueryWrapper<>();
		groupQueryWrapper.lambda().eq(TkDepartGroupMirror::getDepartAttr,"ATRV0000");
		groupQueryWrapper.lambda().eq(TkDepartGroupMirror::getMirrorCode,mirrorCode.substring(0,6));
		List<TkDepartGroupMirror> groups = tkDepartGroupMirrorMapper.selectList(groupQueryWrapper);
		List<String> vitralOrgCodes = new ArrayList<>();
		for(TkDepartGroupMirror tkDepartGroup : groups){
			vitralOrgCodes.add(tkDepartGroup.getIndexDepart());
		}
    	String[] dataTypes = {"kpi","budget"};
		for(String dataType : dataTypes){
			for (int index = 0; index < indexValues.size(); index++) {

				KpiIndexValueVo ivvo = indexValues.get(index);
				String indexValueCode = ivvo.getCode();
				KpiIndexDataVo iData = null;
				if (index >= indexDatas.size()) {
					//
					iData = new KpiIndexDataVo();
					iData.setM01("0.0");
					iData.setM02("0.0");
					iData.setM03("0.0");
					iData.setM04("0.0");
					iData.setM05("0.0");
					iData.setM06("0.0");
					iData.setM07("0.0");
					iData.setM08("0.0");
					iData.setM09("0.0");
					iData.setM10("0.0");
					iData.setM11("0.0");
					iData.setM12("0.0");
					iData.setmTotal("0.0");
					iData.setQ01("0.0");
					iData.setQ02("0.0");
					iData.setQ03("0.0");
					iData.setQ04("0.0");
				} else {
					iData = indexDatas.get(index);
				}

				// 格式化 传入值
				{
					Map<String, Object> beanMap = EsJsonUtils.bean2Map(iData);
					Set<String> keys = new HashSet<String>(beanMap.keySet());
					for (String key : keys) {
						String valueStr = (String) beanMap.get(key);
						valueStr = KpiImportUtils.formatValueStr(valueStr);
						beanMap.put(key, valueStr);
					}
					iData = (KpiIndexDataVo) EsJsonUtils.map2Bean(beanMap, KpiIndexDataVo.class);
				}

				TkIndexValueMirror entity = null;
				{
					Map<String, Object> beanStrMap = EsJsonUtils.bean2Map(iData);
					Map<String, Object> beanDoubleMap = new HashMap<String, Object>();
					Set<Entry<String, Object>> entries = beanStrMap.entrySet();
					for(Entry<String, Object> entry : entries) {
						beanDoubleMap.put(entry.getKey(), 1.0*Double.valueOf((String)entry.getValue()));
					}
					beanDoubleMap.put("MTotal", beanDoubleMap.get("mTotal"));
					entity = (TkIndexValueMirror)EsJsonUtils.map2Bean(beanDoubleMap, TkIndexValueMirror.class);
				}
				if(null == entity) {
					entity = new TkIndexValueMirror();
				}

				entity.setDataType(dataType);

				entity.setMirrorCode(mirrorCode);
				entity.setIndexCode(indexCode);
				entity.setIndexValueCode(indexValueCode);
				entity.setIndexValueStatus("0");
				entity.setYear("2019");
				entity.setIndexScorer(scorer.getUsername());
				entity.setIndexDepart(indexOrgCode);
				entity.setCreateBy("admin");
				entity.setCreateDate(new Date());
				entity.setUpdateBy("admin");
				entity.setUpdateDate(new Date());
				if (!vitralOrgCodes.contains(indexOrgCode) && indexValueCode.equals("KCIAAB017VA001") || indexValueCode.equals("KGIAAB017VA001")) {
					// KCIAAB017VA001 = 重点工作完成
					Map<String,Object> userQueryMap = new HashMap<>();;
					userQueryMap.put("roleCode","ykgm");
					List<String> userNames = commonMapper.getUserNameByByParam(userQueryMap);
					if(userNames.size() > 0){
						for (String userName : userNames){
							// KCIAAB017VA001 = 重点工作完成
							entity.setIndexExecutor(userName);
							entity.setIndexExecutorDepart("A01A01");
							updateIndexMirrorEntity(entity);
						}
					}
				} else if (!vitralOrgCodes.contains(indexOrgCode) && indexValueCode.equals("KCIAAC005VB001") ) {
					// KCIAAC005VB001 = 质量改进情况
					Map<String,Object> userQueryMap = new HashMap<>();;
					userQueryMap.put("roleCode","ykkpiowner");
					List<String> userNames = commonMapper.getUserNameByByParam(userQueryMap);
					if(userNames.size() > 0){
						for (String userName : userNames){
							// KCIAAB017VA001 = 重点工作完成
							entity.setIndexExecutor(userName);
							entity.setIndexExecutorDepart("A01A01");
							updateIndexMirrorEntity(entity);
						}
					}
				}else if("A01A01A01".equals(indexOrgCode.substring(0,9))){
					entity.setIndexExecutor("system");
					entity.setIndexExecutorDepart("A01A01A01");
					updateIndexMirrorEntity(entity);
				}else{
					entity.setIndexExecutor("system");
					entity.setIndexExecutorDepart("A01A01A02");
					updateIndexMirrorEntity(entity);
				}

			}
		}

	}

    private void updateWeightMirrorEntity(TkIndexWeightMirror entity) {
    	QueryWrapper<TkIndexWeightMirror> queryWrapper = new QueryWrapper<TkIndexWeightMirror>();
        queryWrapper.eq("mirror_code", entity.getMirrorCode());
        queryWrapper.eq("index_code", entity.getIndexCode());
        queryWrapper.eq("org_code", entity.getOrgCode());
        TkIndexWeightMirror dbEntity = tkIndexWeightMirrorService.getOne(queryWrapper);
        if (null != dbEntity) {
            String id = dbEntity.getId();
            EsBeanUtils.copyBeanNotNull2Bean(entity, dbEntity);
            dbEntity.setId(id);
            tkIndexWeightMirrorService.updateById(dbEntity);
        } else {
            tkIndexWeightMirrorService.save(entity);
        }
    }

    private void updateIndexMirrorEntity(TkIndexValueMirror entity) {
        QueryWrapper<TkIndexValueMirror> queryWrapper = new QueryWrapper<TkIndexValueMirror>();
        queryWrapper.eq("mirror_code", entity.getMirrorCode());
        queryWrapper.eq("index_depart", entity.getIndexDepart());
		queryWrapper.eq("INDEX_SCORER",entity.getIndexScorer());
        queryWrapper.eq("index_value_code", entity.getIndexValueCode());
		queryWrapper.eq("data_type",entity.getDataType());
        if (null != entity.getIndexExecutor()) {
            queryWrapper.eq("index_executor", entity.getIndexExecutor());
        }
        TkIndexValueMirror dbEntity = tkIndexValueMirrorServiceI.getOne(queryWrapper);

        if (null != dbEntity) {
            String id = dbEntity.getId();
            EsBeanUtils.copyBeanNotNull2Bean(entity, dbEntity);
            dbEntity.setId(id);
            tkIndexValueMirrorServiceI.saveOrUpdate(dbEntity);
        } else {
            tkIndexValueMirrorServiceI.saveOrUpdate(entity);
        }

    }
	
}
